package com.whisperly.echotalk.starryb.schemas;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;

import com.whisperly.echotalk.bean.ApiResponse;
import com.whisperly.echotalk.bean.VersionCheckRequest;
import com.whisperly.echotalk.bean.VersionCheckResponse;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.netWorkUtils.ApiClient;
import com.whisperly.echotalk.starryb.netWorkUtils.ApiService;
import com.whisperly.echotalk.starryb.utils.UpdateNotificationHelper;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class VersionManager {
    private static final String TAG = "VersionManager";
    private static final String PREF_NAME = "version_check";
    private static final String KEY_LAST_CHECK_TIME = "last_check_time";
    private static final long CHECK_INTERVAL = 24 * 60 * 60 * 1000; // 24小时检查一次

    private Context context;
    private VersionCheckListener listener;
    private UpdateNotificationHelper notificationHelper;

    public interface VersionCheckListener {
        void onUpdateAvailable(VersionCheckResponse response);
        void onNoUpdate();
        void onCheckFailed(String error);
    }

    public VersionManager(Context context) {
        this.context = context.getApplicationContext();
        this.notificationHelper = new UpdateNotificationHelper(context);
    }

    /**
     * 静默检查更新（自动检查，根据时间间隔）
     */
    public void checkUpdateSilently() {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        long lastCheckTime = prefs.getLong(KEY_LAST_CHECK_TIME, 0);
        long currentTime = System.currentTimeMillis();

        if (currentTime - lastCheckTime >= CHECK_INTERVAL) {
            checkUpdateInternal(false);
            prefs.edit().putLong(KEY_LAST_CHECK_TIME, currentTime).apply();
        } else {
            Log.d(TAG, "距离上次检查时间未超过间隔，跳过检查");
        }

    }

    /**
     * 内部检查更新方法
     */
    private void checkUpdateInternal(boolean isManual) {
        try {
            VersionCheckRequest request = getVersionCheckRequest();

            Log.d(TAG, "检查更新请求: " + request.toString());

            ApiService apiService = ApiClient.getClient().create(ApiService.class);
            Call<ApiResponse<VersionCheckResponse>> call = apiService.checkVersion(request);

            call.enqueue(new Callback<>() {
                @Override
                public void onResponse(Call<ApiResponse<VersionCheckResponse>> call,
                                       Response<ApiResponse<VersionCheckResponse>> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        ApiResponse<VersionCheckResponse> apiResponse = response.body();
                        if ("200".equals(apiResponse.getCode())) {
                            handleUpdateResponse(apiResponse.getData(), isManual);
                        } else {
                            Log.w(TAG, "检查更新失败: " + apiResponse.getMsg());
                            if (listener != null) {
                                listener.onCheckFailed(apiResponse.getMsg());
                            }
                        }
                    } else {
                        Log.e(TAG, "服务器响应异常");
                        if (listener != null) {
                            listener.onCheckFailed("服务器响应异常");
                        }
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse<VersionCheckResponse>> call, Throwable t) {
                    Log.e(TAG, "检查更新网络请求失败: " + t.getMessage());
                    if (listener != null) {
                        listener.onCheckFailed("网络请求失败: " + t.getMessage());
                    }
                }
            });

        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "获取当前版本信息失败", e);
            if (listener != null) {
                listener.onCheckFailed("获取版本信息失败");
            }
        }
    }

    @NonNull
    private VersionCheckRequest getVersionCheckRequest() throws PackageManager.NameNotFoundException {
        PackageManager pm = context.getPackageManager();
        PackageInfo pInfo = pm.getPackageInfo(context.getPackageName(), 0);

        VersionCheckRequest request = new VersionCheckRequest();
        request.setPlatform("android");
        request.setCurrentVersion(pInfo.versionName);
        request.setCurrentVersionCode(pInfo.getLongVersionCode());
        request.setDeviceModel(Build.MODEL);
        request.setOsVersion(Build.VERSION.RELEASE);
        request.setPackageName(context.getPackageName());
        return request;
    }

    /**
     * 处理更新响应
     */
    private void handleUpdateResponse(VersionCheckResponse response, boolean isManual) {
        Log.d(TAG, "更新检查结果: " + response.toString());

        if (response.getHasUpdate() != null && response.getHasUpdate()) {
            if (listener != null) {
                listener.onUpdateAvailable(response);
            }

            // 如果是手动检查，总是显示结果
            if (isManual) {
                notificationHelper.showUpdateNotification(response);
            } else {
                // 自动检查时，根据设置决定是否显示通知
                notificationHelper.showUpdateNotification(response);
            }
        } else {
            Log.d(TAG, "当前已是最新版本");
            if (listener != null) {
                listener.onNoUpdate();
            }
            
            // 手动检查时，即使没有更新也给用户反馈
            if (isManual) {
                com.hjq.toast.Toaster.show(context.getString(R.string.now_is_new_version));
            }
        }
    }

    /**
     * 获取当前版本信息
     */
    public static String getCurrentVersionName(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pInfo = pm.getPackageInfo(context.getPackageName(), 0);
            return pInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return context.getString(R.string.unknown);
        }
    }
}